import { Question, SelectLang } from '@/components/RightContent';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { AvatarDropdown, AvatarName } from './components/RightContent/AvatarDropdown';
import { errorConfig } from './requestErrorConfig';
import { myself } from './services/login';
import { useEffect } from 'react';
import { message, notification } from 'antd';
import { warning_list } from './services/sickbeds';
import { useModel } from 'umi';
import { WebSocketInit, ws } from './utils/webSocket';
import globalKey from '@/utils/globalkey';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/login';
const sharePath = '/broadcast/broadcast_share';
const h5Path1 = '/h5_agreement/privacy_policy';
const h5Path2 = '/h5_agreement/term_of_service';
const bigDataPath = '/big_data_screen';
const familyBedPath='/family_bed_screen';

const h5Path3 = '/h5_familysickbed/jianhu_hospital';
const h5Path4 = '/h5_physiologicalmonitoring/blosugarCharts';
const h5Path5 = '/h5_physiologicalmonitoring/temperCharts';
const h5Path6 = '/h5_physiologicalmonitoring/oxiCharts';
const h5Path7 = '/h5_physiologicalmonitoring/hamCharts';
const h5Path8 = '/h5_physiologicalmonitoring/physiologicalmonitoring';
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await myself();
      console.log('登录信息', msg);
      if (msg.data.is_master == 1) {
        msg.data['authArray'] = [1];
        // console.log(1)
      } else {
        //  msg.data['authArray'] = res.data;
        // console.log(2)
      }
      //登录长连接
      WebSocketInit(msg.data.current_platform_id);
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const { location } = history;
  if (
    location.pathname !== loginPath &&
    !history.location.pathname.includes(sharePath) &&
    !history.location.pathname.includes(h5Path8) &&
    !history.location.pathname.includes(h5Path7) &&
    !history.location.pathname.includes(h5Path6) &&
    !history.location.pathname.includes(h5Path5) &&
    !history.location.pathname.includes(h5Path4) &&
    !history.location.pathname.includes(h5Path3) &&
    !history.location.pathname.includes(h5Path2) &&
    !history.location.pathname.includes(h5Path1) &&
    !history.location.pathname.includes(bigDataPath)&&
    !history.location.pathname.includes(familyBedPath)
  ) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  // 存储未处理呼叫个数
  const { count, setCount, sickbedWarningVisible, setsickbedWarningVisible } = useModel('SickbedWarningModel', (model) => ({
    count: model.count,
    setCount: model.setCount,
    sickbedWarningVisible: model.sickbedWarningVisible,
    setsickbedWarningVisible: model.setsickbedWarningVisible
  }));

  function isValidJSON(text: any) {
    try {
      let result = JSON.parse(text);
      return result;
    } catch (error) {
      return false;
    }
  }

  useEffect(() => {
    // 获取未处理呼叫个数
    const get_warning_list = async () => {
      //默认分页参数和后端接口字段不匹配
      let request_body = {
        current: 1,
        pageSize: 10,
        status: 0,
      };
      let res: any = await warning_list(request_body)
      console.log('呼叫提醒列表', res);
      if (res.code == 200) {
        if (res.data.total_count > 0) {
          //开启弹窗
          setsickbedWarningVisible(true)
          //设置数量
          setCount(res.data.total_count)
        }
      }
    }
    get_warning_list();
    return () => {
      ws.close(); // 组件卸载时关闭连接
    };
  }, [])

  // 监听count变化
  useEffect(() => {
    console.log(count);
    showNotification(count, sickbedWarningVisible);
  }, [count, sickbedWarningVisible])

  // 显示通知框的方法
  const showNotification = (count: number, sickbedWarningVisible: boolean) => {
    if (count > 0 && sickbedWarningVisible && (initialState?.currentUser?.authArray.includes('callReminder') || initialState?.currentUser?.is_master == 1) && initialState?.currentUser?.current_platform.model_permissions?.includes('familySickbeds')) {
      notification.open({
        message: '呼叫提醒',
        description: <a>存在<span style={{ color: "red" }}>{count}</span>条未处理的呼叫信息，请前往处理。</a>,
        duration: 0,
        placement: 'bottomRight',
        key: globalKey.sickbedWarningNotification,
        onClose: () => {
          //关闭弹窗
          setsickbedWarningVisible(false)
        },
        onClick: () => {
          //关闭弹窗
          setsickbedWarningVisible(false)
          history.push('/familySickbeds/callReminder')
        }
      });
    } else {
      notification.destroy(globalKey.sickbedWarningNotification)
    }
  }

  // 监听长连接消息

  console.log('app.tsx onmessage');

  ws.onmessage = (m: any) => {
    console.log('app.tsx', m.data);
    const result = isValidJSON(m.data)
    if (result) {
      if (result.type == 'sickbedWarning' && (initialState?.currentUser?.authArray.includes('callReminder') || initialState?.currentUser?.is_master == 1) && initialState?.currentUser?.current_platform.model_permissions?.includes('familySickbeds')) {
        setCount((count: number) => {
          console.log('count', count);
          return count + 1;
        })
        // 新增弹窗
        notification.open({
          message: '呼叫提醒',
          description: <a>您有一条新的呼叫提醒，请前往处理。</a>,
          duration: 20,
          key: count,
          placement: 'bottomRight',
          onClose: () => {

          },
          onClick: () => {
            //关闭弹窗
            notification.destroy(count)
            history.push('/familySickbeds/callReminder')
          }
        });
      }
    }
  };
  return {
    actionsRender: () => [<Question key="doc" />, <SelectLang key="SelectLang" />],
    avatarProps: {
      // 设置头像
      src:
        initialState?.currentUser?.head_img === ''
          ? 'https://lmn-beta-operation-new.limaoniao.com.cn/log1.png'
          : initialState?.currentUser?.head_img,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    // 去掉水印
    // waterMarkProps: {
    //   content: initialState?.currentUser?.name,
    // },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (
        (!initialState?.currentUser || initialState?.currentUser.length == 0) &&
        location.pathname !== loginPath &&
        !history.location.pathname.includes(h5Path8) &&
        !history.location.pathname.includes(h5Path7) &&
        !history.location.pathname.includes(h5Path6) &&
        !history.location.pathname.includes(h5Path5) &&
        !history.location.pathname.includes(h5Path4) &&
        !history.location.pathname.includes(h5Path3) &&
        !history.location.pathname.includes(h5Path2) &&
        !history.location.pathname.includes(h5Path1) &&
        !history.location.pathname.includes(bigDataPath)&&
        !history.location.pathname.includes(familyBedPath)
      ) {
        history.push(loginPath);
      }
    },
    layoutBgImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    // links: isDev
    //   ? [
    //       <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
    //         <LinkOutlined />
    //         <span>OpenAPI 文档</span>
    //       </Link>,
    //     ]
    //   : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    // childrenRender: (children) => {
    //   // if (initialState?.loading) return <PageLoading />;
    //   return (
    //     <>
    //       {children}
    //       <SettingDrawer
    //         disableUrlParams
    //         enableDarkTheme
    //         settings={initialState?.settings}
    //         onSettingChange={(settings) => {
    //           setInitialState((preInitialState) => ({
    //             ...preInitialState,
    //             settings,
    //           }));
    //         }}
    //       />
    //     </>
    //   );
    // },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
